package com.godofball.todo.interceptor;


import com.alibaba.fastjson.JSON;
import com.godofball.todo.entity.utils.AppHttpCodeEnum;
import com.godofball.todo.entity.utils.ResponseResult;
import com.godofball.todo.utils.BaseContext;
import com.godofball.todo.utils.JwtHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        log.info(request.getRequestURI());
        log.info(request.toString());
        String token = request.getHeader("token");
        log.info(token);
        if (StringUtils.isEmpty(token)) {
            response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN)));
            return false;
        }
        if (!JwtHelper.verifyToken(token)) {
            response.getWriter().write(JSON.toJSONString(ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_OVERDUE)));
            return false;
        }
        System.out.println("valid token");
        //在当前线程保存用户
        String userId = JwtHelper.getUsername(token);
        BaseContext.setCurrentUser(userId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器处理结束...");
        //移除当前线程用户ID
        BaseContext.removeCurrentUser();
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求结束...");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
